from flask import Flask, request, jsonify
from flask_cors import CORS
import pymysql
app = Flask(__name__)
CORS(app)
# 配置数据库连接参数
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'db': 'test',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}
# 获取所有记录
@app.route('/info', methods=['GET'])
def get_all_ass():
    """
    获取数据库中的所有记录并以JSON格式返回。
    Returns:
        jsonify: 包含所有记录的JSON响应，或在无记录时返回404错误。
    """
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM ass")
            rows = cursor.fetchall()
        if not rows:
            return jsonify({'message': 'No records found'}), 404
        return jsonify(rows)
    finally:
        connection.close()
# 创建信息
@app.route('/info/add', methods=['POST'])
def create_ass():
    """
    创建一条新的记录。
    Returns:
        jsonify: 包含成功消息的JSON响应，或在请求数据不完整时返回400错误。
    """
    if not request.json:
        return jsonify({'error': '请求格式错误'}), 401
    required_fields = [
        'company_name', 'english_name', 'unified_social_credit_code', 'company_type',
        'operating_status', 'establishment_date', 'approval_date', 'legal_representative',
        'registered_capital', 'paid_in_capital', 'insured_persons', 'company_scale',
        'business_scope', 'registered_address', 'business_term', 'taxpayer_identification_number',
        'business_registration_number', 'organization_code', 'contact_number', 'email',
        'taxpayer_qualification', 'former_name', 'province', 'city', 'district', 'website_link',
        'industry', 'first_level_industry_classification', 'second_level_industry_classification',
        'third_level_industry_classification', 'registration_authority', 'longitude', 'latitude', 'ai'
    ]
    data = request.json
    missing_fields = [field for field in required_fields if field not in data]
    if missing_fields:
        return jsonify({'error': '缺少必填字段', 'missing_fields': missing_fields}), 400
    if not data.get('unified_social_credit_code'):
        return jsonify({'error': '统一社会信用代码不能为空'}), 402
    columns = ', '.join(required_fields)
    placeholders = ', '.join(['%s'] * len(required_fields))
    query = f"INSERT INTO ass ({columns}) VALUES ({placeholders})"
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            cursor.execute(query, [data[field] for field in required_fields])
        connection.commit()
    except Exception as e:
        if 'Duplicate entry' in str(e) and 'unified_social_credit_code' in str(e):
            return jsonify({'error': '统一社会信用代码已存在'}), 403
        else:
            return jsonify({'error': str(e)}), 500
    finally:
        connection.close()
    return jsonify({'message': '记录创建成功'}), 201
# 根据ID获取用户信息
@app.route('/info/<int:id>', methods=['GET'])
def get_ass(id):
    """
    根据ID获取单条记录。
    Args:
        id (int): 记录的ID。
    Returns:
        jsonify: 包含所请求记录的JSON响应，或在记录不存在时返回404错误。
    """
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM ass WHERE id = %s", (id,))
            row = cursor.fetchone()
        if row is None:
            return jsonify({'error': 'No record found'}), 404
        else:
            return jsonify(row)
    finally:
        connection.close()
# 根据ID更新用户信息
@app.route('/info/<int:id>', methods=['PUT'])
def update_ass(id):
    """
    根据ID更新记录。
    Args:
        id (int): 记录的ID。
    Returns:
        jsonify: 包含成功消息的JSON响应，或在请求数据不完整时返回400错误。
    """
    if not request.json:
        return jsonify({'error': 'Bad request'}), 400
    data = request.json
    fields = [
        'company_name', 'english_name', 'unified_social_credit_code', 'company_type',
        'operating_status', 'establishment_date', 'approval_date', 'legal_representative',
        'registered_capital', 'paid_in_capital', 'insured_persons', 'company_scale',
        'business_scope', 'registered_address', 'business_term', 'taxpayer_identification_number',
        'business_registration_number', 'organization_code', 'contact_number', 'email',
        'taxpayer_qualification', 'former_name', 'province', 'city', 'district', 'website_link',
        'industry', 'first_level_industry_classification', 'second_level_industry_classification',
        'third_level_industry_classification', 'registration_authority', 'longitude', 'latitude', 'ai'
    ]
    set_clause = ', '.join([f"{field}=%s" for field in fields])
    values = [data.get(field, None) for field in fields]
    if all(v is None for v in values):
        return jsonify({'error': 'No data provided to update'}), 400
    query = f"UPDATE ass SET {set_clause} WHERE id = %s"
    values.append(id)
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            cursor.execute(query, values)
        connection.commit()
    except Exception as e:
        return jsonify({'error': str(e)}), 500
    finally:
        connection.close()
    return jsonify({'message': f'Record {id} updated'})
# 根据ID删除用户信息
@app.route('/info/<int:id>', methods=['DELETE'])
def delete_ass(id):
    """
    根据ID删除记录。
    Args:
        id (int): 记录的ID。
    Returns:
        jsonify: 包含成功消息的JSON响应。
    """
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            cursor.execute("DELETE FROM ass WHERE id = %s", (id,))
        connection.commit()
    finally:
        connection.close()
    return jsonify({'message': f'Record {id} deleted'})
# 根据公司名称搜索
@app.route('/info/search', methods=['GET'])
def search_by_name():
    query = request.args.get('query', '').strip()
    if not query:
        return jsonify({'message': 'Query parameter is required'}), 400
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM ass WHERE company_name LIKE %s", ('%' + query + '%',))
            rows = cursor.fetchall()
        if not rows:
            return jsonify({'message': 'No matching records found', 'query': query}), 404
        return jsonify(rows), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500
    finally:
        connection.close()
if __name__ == '__main__':
    app.run(debug=False)  # 在生产环境中禁用调试模式
